package stc.skymobi.demo.test;

import com.alibaba.fastjson.JSON;
import com.google.common.io.ByteStreams;
import com.skymobi.netty.demo.bean.GetUrlRequest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import stc.skymobi.bean.tlv.encode.TLVEncoderOfBean;
import stc.skymobi.netty.util.NettyConstants;
import stc.skymobi.util.ByteUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@ContextConfiguration({"classpath*:test.xml"
        , "classpath*:unitrepo/stc/template/protocol/stcDefaultSerializationCodec.xml"})
public class HttpClient extends AbstractJUnit4SpringContextTests {
    @Autowired
    private TLVEncoderOfBean tlvBeanEncoder;

    @Test
    public void json() {
        GetUrlRequest request = new GetUrlRequest();
        request.setToken(10086);
        request.setUrl("http://wap.baidu.com");
        String resp = post("http://localhost:100/getUrl", JSON.toJSONString(request).getBytes(), NettyConstants.JSON_TYPE);
        System.out.println(resp);
    }

    @Test
    public void tlv() {
        GetUrlRequest request = new GetUrlRequest();
        request.setToken(10086);
        request.setUrl("http://wap.baidu.com");
        byte[] bytes = ByteUtils.union(
                tlvBeanEncoder.encode(request,
                        tlvBeanEncoder.getEncodeContextFactory().createEncodeContext(
                                request.getClass(), null)
                )
        );
        String resp = post("http://localhost:100/getUrl", bytes, NettyConstants.TLV_TYPE);
        System.out.println(resp);
    }

    public static String post(String url, byte[] body, String contentType) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URI(url).toURL().openConnection();

            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("uuid", UUID.randomUUID().toString());
            conn.getOutputStream().write(body);

            contentType = conn.getContentType();
            String encoding = "utf-8";
            if (contentType != null && contentType.indexOf("charset=") > 0) {
                encoding = contentType.split("charset=")[1];
            }
            Map<String, List<String>> headers = conn.getHeaderFields();
            for (String key : headers.keySet()) {
                System.out.println(key + ":" + headers.get(key));
            }

            InputStream is = conn.getInputStream();
            byte[] resp = ByteStreams.toByteArray(is);
            conn.disconnect();
            return new String(resp, encoding);
        } catch (URISyntaxException | IOException e) {
            return "";
        }
    }
}
